/* this function disposes the sending frame, each sub-frame is equal or less */
/* than PUB_MAX_FRAME_LENGTH (defined in public.h) characters */

#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	"public.h"
#include 	"msgbus_lib.h"

#if !lint
static char Sccsid[] = {"%Z% %M% %I% %G%"};
#endif /* !lint */


short
frame_dispose(char *frame_ptr, int frame_size, char **send_ptr, int *send_size, char **remain_ptr, int *remain_size)
{
	short	end_flag, frame_no;
	char	*ptr_send, *ptr_remain;

	memcpy(&frame_no, frame_ptr + sizeof(short), sizeof(short));
	end_flag = 1;
	if (frame_size <= PUB_MAX_FRAME_LENGTH)
	{
		*send_ptr = frame_ptr;
		memcpy(*send_ptr, &end_flag, sizeof(short));
		*send_size = frame_size;
		*remain_ptr = NULL;
		*remain_size = 0;
		return frame_no;
	}

	/* if frame_size larger than MAX_FRAME_LENGTH, than dispose it */
	ptr_send = (char *) malloc(PUB_MAX_FRAME_LENGTH);
	if (ptr_send == NULL)
	{
		printf("memory allocate error!\n");
		return -1;
	}
	ptr_remain = (char *) malloc(frame_size - PUB_MAX_FRAME_LENGTH + 4);
	if (ptr_remain == NULL)
	{
		printf("memory allocate error!\n");
		free(ptr_send);
		return -1;
	}

	end_flag = 0;
	memcpy(ptr_send, frame_ptr, PUB_MAX_FRAME_LENGTH);
	memcpy(ptr_send, &end_flag, sizeof(short));

	memcpy(ptr_remain, &end_flag, sizeof(short));
	frame_no += 1;
	memcpy(ptr_remain + sizeof(short), &frame_no, sizeof(short));
	memcpy(ptr_remain + 4, frame_ptr + PUB_MAX_FRAME_LENGTH, frame_size - PUB_MAX_FRAME_LENGTH);

	*send_ptr = ptr_send;
	*send_size = PUB_MAX_FRAME_LENGTH;
	*remain_ptr = ptr_remain;
	*remain_size = frame_size - PUB_MAX_FRAME_LENGTH + 4;

	free(frame_ptr);

	return frame_no - 1;

}

int dnet_send_message_frame(system_net_info &net_info, int report_type, app_buf_head &ah, char *result_buf, int result_len)
{
	char		*input_ptr, *send_ptr, *remain_ptr;
	int			input_size, send_size, remain_size;
	int return_no;
	int ret;

				input_ptr = result_buf;
				input_size = result_len;
				while (input_ptr != NULL)
				{
					return_no = frame_dispose(input_ptr, input_size, &send_ptr, &send_size, &remain_ptr, &remain_size);
					if (return_no < 0)
						break;

					ret=net_info.dnet_send_message(
							DNET_REPORT_POINT_TO_POINT,
     				       	report_type,
       				        ah.rhead.sour_host,
         	 				ah.rhead.sour_process_name,
          	   				send_ptr, send_size);

					if (ret >= 0){
						TRACE_INFO( "result frame %d send succeed! \n", return_no);
					}
					else{
						TRACE_ERROR( "result frame %d send fail! \n", return_no);
					}
					if (send_ptr != NULL)
  					{
     					free(send_ptr);
						send_ptr = NULL;
  					}
					input_ptr = remain_ptr;
					input_size = remain_size;
				}
				return 1;
}
